import { defineStore } from "pinia";
import { getCurrentUser, getSomeShmetroConfig } from "../request/system";
import GLOBAL from "../utils/globelConfig";
import type { ISystemConfig } from "./storeType";
import { isInnerNet } from "../utils/utils";
import { cookie } from "../utils/cookie";

export const useUserStore = defineStore("user", {
  state: () => ({
    userInfo: {},
    systemConfigMap: {} as ISystemConfig,
    isInnerNetFlag: false,
  }),
  actions: {
    getUserInfo() {
      // 获取系统配置
      let param = {
        config:
          "history_video,inner_host_name,outer_host_name,inner_host_supermap,video_http_path,video_nginx_path", //多个配置以逗号间隔
        host: import.meta.env.DEV ? "172.20.62.103" : "172.20.62.235",
      };
      if (Object.keys(this.systemConfigMap).length === 0) {
        getSomeShmetroConfig(param).then((res: any) => {
          if (res.code == 200) {
            // 如果访问的是https协议，则所有http接口换成https
            if (window.location.href.startsWith("https:")) {
              let url;
              for (let k in res.bodyData) {
                url = res.bodyData[k];
                if (url.startsWith("http")) {
                  url = url.replace("http", "https");
                } else if (url.startsWith("ws")) {
                  url = url.replace("ws", "wss");
                }
                this.systemConfigMap[k] = url;
              }
            } else {
              this.systemConfigMap = res.bodyData;
            }
            if (isInnerNet(document.domain)) {
              this.isInnerNetFlag = true;
            } else {
              this.isInnerNetFlag = false;
            }
          }
        });
      }
      // 获取用户信息
      getCurrentUser().then((res: any) => {
        // console.log("getCurrentUser", res);
        if (res.bodyData) {
          this.userInfo = res.bodyData;
        } else {
          if (!cookie.get("AUTHORIZATION")) {
            window.location.href = GLOBAL.LOGIN_URL;
          }
        }
      });
    },
  },
});
